//
//  UserModel.m
//  Penetration
//
//  Created by lwx on 17/5/4.
//  Copyright © 2017年 Lwx. All rights reserved.
//

#import "UserModel.h"

static UserModel *currentUser;
static dispatch_once_t onceToken;

static NSString * const LoginKey = @"MyLoginKey";

@implementation UserModel

+ (NSDictionary *)modelCustomPropertyMapper{
    return @{
             @"userId":@"id",
             };
    
}

- (void)encodeWithCoder:(NSCoder*)aCoder {
    [self yy_modelEncodeWithCoder:aCoder];
}

- (id)initWithCoder:(NSCoder*)aDecoder
{
    self = [super init];
    return [self yy_modelInitWithCoder:aDecoder];
}

- (id)copyWithZone:(NSZone*)zone {
    return [self yy_modelCopy];
}

- (NSUInteger)hash {
    return [self yy_modelHash];
}

- (BOOL)isEqual:(id)object {
    return [self yy_modelIsEqual:object];
}

//获取当前用户
+ (instancetype)intance
{
    if(currentUser == nil)
    {
        dispatch_once(&onceToken, ^{
            currentUser = [[UserModel alloc] init];
        });
    }
    return currentUser;
}

+ (void)attempDealloc
{
    onceToken = 0;
    currentUser = nil;
    [UserModel deleteLogin];
}

//保存登录
+ (void)saveLogin
{
    NSUserDefaults *mydefault = [NSUserDefaults standardUserDefaults];
    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:[UserModel intance]];
    [mydefault setObject:data forKey:LoginKey];
    [mydefault synchronize];
}

//删除保存记录
+ (void)deleteLogin
{
    NSUserDefaults *mydefault = [NSUserDefaults standardUserDefaults];
    [mydefault removeObjectForKey:LoginKey];
    [mydefault removeObjectForKey:@"kIsVoice"];
    [mydefault removeObjectForKey:@"kIsZD"];
}

//是否有保存数据
+ (BOOL)isSaveLogin
{
    NSUserDefaults *mydefault = [NSUserDefaults standardUserDefaults];
    if ([mydefault objectForKey:LoginKey] != nil)
    {
        [UserModel getLogin];
        return YES;
    }
    return NO;
}

//只判断，不获取
+ (BOOL)isSaveLoginNotGet
{
    NSUserDefaults *mydefault = [NSUserDefaults standardUserDefaults];
    if ([mydefault objectForKey:LoginKey] != nil)
    {
        return YES;//登录成功
    }
    return NO;
}

//获取保存数据
+ (void)getLogin
{
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSData *data = [user objectForKey:LoginKey];
    [[UserModel intance]setIntance:[NSKeyedUnarchiver unarchiveObjectWithData:data]];
}

- (void)setIntance:(UserModel *)model
{
    currentUser = model;
}

@end
